package com.xd.pre.modules.tpshop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xd.pre.log.domain.SysLog;
import com.xd.pre.modules.tpshop.domain.*;
import com.xd.pre.modules.tpshop.mapper.TpOrderMapper;
import com.xd.pre.modules.tpshop.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xd.pre.modules.tpshop.util.CommonFunction;
import com.xd.pre.modules.tpshop.virtuaBean.OrderVirtual2App;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lx
 * @since 2020-06-03
 */
@Service
public class TpOrderServiceImpl extends ServiceImpl<TpOrderMapper, TpOrder> implements ITpOrderService {

    @Autowired
    private ITpOrderGoodsService og_biz;

    @Autowired
    private ITpUserAddressService address_biz;
    @Autowired
    private ITpShippingService ship_biz;
    @Autowired
    private ITpPaymentService pay_biz;
    @Autowired
    private TpOrderMapper orderMapper;


    @Override
    public OrderVirtual2App get_OrderVirtual2App(TpOrder order) { //通用方法
        List<TpOrderGoods> og_list = og_biz.findByOrderId(order.getOrderId());
        TpUserAddress adress = address_biz.findUserAddress_byKeyId(order.getAddressId());
        TpShipping ship = ship_biz.find_byKeyId(order.getShippingId());
        TpPayment pay = pay_biz.find_byKeyId(order.getPaymentId()); // 提交订单的时候  它为null ！
        if (!CommonFunction.poCheckNotNull(pay)) { //if 是提交订单的时候 即不是 查阅历史订单的时候！
            System.out.println("channel——1-您当前是在提交订单！或者app没有实现支付功能");
            return new OrderVirtual2App(
                    order.getOrderId(),
                    order.getOrderSn(),
                    order.getUserId(),

                    order.getOrderStatus(),
                    order.getShippingStatus(),
                    order.getPayStatus(),

                    //				order.getAddressId(),
                    //				order.getShippingId(),
                    //				order.getPaymentId(),
                    adress.getConsignee(),
                    adress.getProvince(),
                    adress.getCity(),
                    adress.getDistrict(),
                    adress.getTwon(),
                    adress.getAddress(),
                    adress.getMobile(),
                    adress.getEmail(),
                    0,            //pay.getIsCod(),
                    "",            //pay.getPayCode(),
                    "",            //pay.getPayName(),
                    ship.getShippingCode(),
                    ship.getShippingName(),

                    order.getInvoiceTitle(),

                    order.getGoodsPrice().doubleValue(),
                    order.getShippingPrice().doubleValue(),
                    order.getUserMoney().doubleValue(),
                    order.getCouponPrice().doubleValue(),
                    order.getIntegral(),
                    order.getIntegralMoney().doubleValue(),
                    order.getOrderAmount().doubleValue(),
                    order.getTotalAmount().doubleValue(),
                    order.getAddTime(),

                    order.getShippingTime(),
                    order.getConfirmTime(),
                    order.getPayTime(),

                    order.getOrderPromId(),
                    order.getOrderPromAmount().doubleValue(),

                    order.getDiscount().doubleValue(),
                    order.getUserNote(),
                    order.getAdminNote(),
                    order.getParentSn(),
                    order.getIsDistribut(),

                    order.getPayBtn(),
                    order.getCancelBtn(),
                    order.getReceiveBtn(),
                    order.getCommentBtn(),
                    order.getShippingBtn(),
                    order.getReturnBtn(),
                    order.getOrderStatusCode(),
                    order.getOrderStatusDesc(),

                    og_list
            );
        } else {
            System.out.println("channel——2-您当前是在 查阅历史订单订单！");
            return new OrderVirtual2App(    // 查阅历史订单的时候！即： 不是 提交订单的时候
                    order.getOrderId(),
                    order.getOrderSn(),
                    order.getUserId(),

                    order.getOrderStatus(),
                    order.getShippingStatus(),
                    order.getPayStatus(),

                    //				order.getAddressId(),
                    //				order.getShippingId(),
                    //				order.getPaymentId(),
                    adress.getConsignee(),
                    adress.getProvince(),
                    adress.getCity(),
                    adress.getDistrict(),
                    adress.getTwon(),
                    adress.getAddress(),
                    adress.getMobile(),
                    adress.getEmail(),
                    pay.getIsCod(),
                    pay.getPayCode(),
                    pay.getPayName(),
                    ship.getShippingCode(),
                    ship.getShippingName(),

                    order.getInvoiceTitle(),

                    order.getGoodsPrice().doubleValue(),
                    order.getShippingPrice().doubleValue(),
                    order.getUserMoney().doubleValue(),
                    order.getCouponPrice().doubleValue(),
                    order.getIntegral(),
                    order.getIntegralMoney().doubleValue(),
                    order.getOrderAmount().doubleValue(),
                    order.getTotalAmount().doubleValue(),
                    order.getAddTime(),

                    order.getShippingTime(),
                    order.getConfirmTime(),
                    order.getPayTime(),

                    order.getOrderPromId(),
                    order.getOrderPromAmount().doubleValue(),

                    order.getDiscount().doubleValue(),
                    order.getUserNote(),
                    order.getAdminNote(),
                    order.getParentSn(),
                    order.getIsDistribut(),

                    order.getPayBtn(),
                    order.getCancelBtn(),
                    order.getReceiveBtn(),
                    order.getCommentBtn(),
                    order.getShippingBtn(),
                    order.getReturnBtn(),
                    order.getOrderStatusCode(),
                    order.getOrderStatusDesc(),

                    og_list
            );
        }


    }

    @Override
    public int update_orderStatusTo3_whenCancelOrder(int orderId, int user_id) {
        TpOrder oo = new TpOrder();
        oo.setOrderStatus(3);
        LambdaQueryWrapper<TpOrder> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TpOrder::getOrderId, orderId);
        lambdaQuery.eq(TpOrder::getUserId, user_id);
        int update = orderMapper.update(oo, lambdaQuery);
        return update;
    }

    @Override
    public TpOrder findOrder(int orderId, int userId) {
        LambdaQueryWrapper<TpOrder> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TpOrder::getOrderId, orderId);
        lambdaQuery.eq(TpOrder::getUserId, userId);
        TpOrder one = getOne(lambdaQuery);
        return one;
    }

    @Override
    public TpOrder findOrder_byKeyId(int parseInt) {
        return getById(parseInt);
    }

    @Override
    public int update_confirmOrder_has_paytime(int orderId) {
        return orderMapper.update_confirmOrder_has_paytime(orderId);
    }

    @Override
    public int update_confirmOrder_no_paytime(int orderId) {
        return orderMapper.update_confirmOrder_no_paytime(orderId);
    }

    @Override
    public IPage<TpOrder> findList_byCondition(String condition, int pageIndex, int pageSize, TpOrder dto) {
        Page<TpOrder> logPage = new Page<>(pageIndex, pageSize);

        LambdaQueryWrapper<TpOrder> queryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotEmpty(dto.getOrderSn())) {
            queryWrapper.like(TpOrder::getOrderSn, dto.getOrderSn());
        }

        if(condition.equals("all")) {            //all

        }else if(condition.equals("waitPay")) {        //"待支付"
            queryWrapper.eq(TpOrder::getPayStatus, 0);
            queryWrapper.eq(TpOrder::getOrderStatus, 0);
            queryWrapper.ne(TpOrder::getPaymentId, 2);
        }else if(condition.equals("waitReceive")){					//"待收货"
            queryWrapper.eq(TpOrder::getShippingStatus, 1);
            queryWrapper.eq(TpOrder::getOrderStatus, 1);
        }else if(condition.equals("waitSend")) {//"待发货"
//            queryWrapper.and(wrapper1 -> wrapper1.eq(TpOrder::getPayStatus, 1))
//                    .or(wrapper2 -> wrapper2.eq(TpOrder::getPayStatus, 2));
//            queryWrapper.and(wrapper3 -> wrapper3.ne(TpOrder::getShippingStatus, 1).in(TpOrder::getOrderStatus, "0,1"));

            //https://www.jianshu.com/p/271a64a3bab6  lambdaQueryWrapper复杂用法

            queryWrapper.and(wrapper -> wrapper.eq(TpOrder::getPayStatus, 1).or().eq(TpOrder::getPayStatus, 2));
            queryWrapper.and(wrapper3 -> wrapper3.ne(TpOrder::getShippingStatus, 1).in(TpOrder::getOrderStatus, "0,1"));
        }else if(condition.equals("waitComment")){//"待评价"
            queryWrapper.eq(TpOrder::getOrderStatus, 2);
        }else if(condition.equals("commented")) {//"已完成(已评价)"
            queryWrapper.eq(TpOrder::getOrderStatus, 4);
        }else if(condition.equals("returned"))  { 			//"已作废(已退货?)"
            queryWrapper.eq(TpOrder::getOrderStatus, 5);
        }
        queryWrapper.orderByDesc(TpOrder::getOrderId);

        Page<TpOrder> tpOrderPage = baseMapper.selectPage(logPage, queryWrapper);
        return tpOrderPage;

    }

    /*  findList_byCondition 替换之 findList_byCondition2

    // 注意：分页这块 不能用sql语句(只能用hql语句)，否则会报莫名其妙的错误！！！
	//   分页
	//page:当前页数			: 由app端传入
	//pageSize:每页资料数!!!	: 由app端传入 或server端定义 都可以
	//(page-1)*pageSize:当前页的第一条资料的 分页编号数!!!	o.`order_id`
	@SuppressWarnings("unchecked")
	public Map<String, List> findList_byCondition2(String condition, Integer pageIndex, Integer pageSize) { //
		String hql1 = "FROM TpOrder WHERE 1=1 ";
		String hql2 = "SELECT COUNT(*) FROM TpOrder WHERE 1=1 ";
		if(condition.equals("all")){			//all
			String t = "";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("waitPay"))	{		//"待支付"
			String t = "AND payStatus = 0 AND orderStatus = 0 AND paymentId !=2";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("waitReceive")){					//"待收货"
			String t = "AND shippingStatus=1 AND orderStatus = 1 ";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("waitSend")) {//"待发货"
			String t = "AND (payStatus=1 OR paymentId=2) AND shippingStatus !=1 AND orderStatus IN(0,1)";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("waitComment")){//"待评价"
			String t = "AND orderStatus=2";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("commented")) {//"已完成(已评价)"
			String t = "AND orderStatus = 4";
			hql1 += t;
			hql2 += t;
		}
		if(condition.equals("returned"))  { 										//"已作废(已退货?)"
			String t = "AND orderStatus = 5";
			hql1 += t;
			hql2 += t;
		}
		hql1 +="ORDER BY orderId DESC";

		Query query1=getSession().createQuery(hql1) //createSQLQuery
//				.addEntity("tp_order", TpOrder.class)
//				.addScalar("order_id",Hibernate.INTEGER)
				;
		query1.setFirstResult((pageIndex-1)*pageSize);
        query1.setMaxResults(pageSize);
        List<TpOrder> list1 = query1.list();
//		List<TpOrder> list = query.setFirstResult((pageIndex-1)*pageSize).setMaxResults(pageSize).list(); //或者直接用这一句

        System.out.println("测试-98-dao："+ list1.size());

        Query query2=getSession().createQuery(hql2)	//createSQLQuery
//				.addEntity("tp_order", TpOrder.class)
//				.addScalar("order_id",Hibernate.INTEGER)
				;
//        List list2 = query2.list(); //里面只有一个 string类型的 数值
        Long count = (Long) query2.uniqueResult();
        List<Long> list2 = null;
		if(count > 0){
			list2 = new ArrayList<Long>();
			list2.add(count);
		}

		System.out.println("测试-96-dao："+ list2.size());
		System.out.println("测试-97-dao："+ list2.get(0) );

        Map<String, List> map = null;
		if(CommonFunction.listCheckNotNull(list1 ) && CommonFunction.listCheckNotNull(list2 )) {
			map = new HashMap<String, List>();
			map.put("order_list_byPage_byCondition", list1);
			map.put("order_list_total_byCondition",  list2 );// Integer.parseInt(list2.get(0).toString())  COUNT(*)计算出来的结果数据BigInteger类型，不能直接强转为Integer类型！
			return map;
		}

		return null;//如果 map = null则 则证明就没有 走上面的if ！故list1和list2都为空！！！
	}


    */

    @Override
    public TpOrder findOrder_by_order_sn(String order_sn) {
        LambdaQueryWrapper<TpOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TpOrder::getOrderSn,order_sn);
        TpOrder one = getOne(wrapper);
        return one;
    }

    @Override
    public int findOrderLimit_inToday(int user_id) {
        return orderMapper.findOrderLimit_inToday(user_id);
    }


}
